package com.XZDP.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.XZDP.dto.Result;
import com.XZDP.dto.UserDTO;
import com.XZDP.entity.Follow;
import com.XZDP.mapper.FollowMapper;
import com.XZDP.service.IFollowService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.XZDP.service.IUserService;
import com.XZDP.utils.Constant.RedisConstant;
import com.XZDP.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;


@Service
@Slf4j
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {

    @Autowired
    private FollowMapper followMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private IUserService userService;
    private ObjectMapper objectMapper = new ObjectMapper();

    public Result Concern(Long id) {
        Follow follow = new Follow();
        follow.setUserId(UserHolder.getUser().getId());
        follow.setFollowUserId(id);
        save(follow);
        //存入缓存set类型
        redisTemplate.opsForSet().add(RedisConstant.FOLLOW_KEY + UserHolder.getUser().getId(), id.toString());
        return Result.ok();
    }

    public Result Close(Long id) {
        followMapper.removeID(UserHolder.getUser().getId(), id);
        redisTemplate.opsForSet().remove(RedisConstant.FOLLOW_KEY + UserHolder.getUser().getId(), id.toString());
        return Result.ok();
    }


    public Boolean isFollow(Long id) {
        Long count = followMapper.isFollow(UserHolder.getUser().getId(), id);
        if (count > 0) {
            return true;
        }
        return false;
    }


    public Result CommonFollow(Long id) {
        Long userid = UserHolder.getUser().getId();
        Set<String> intersect = redisTemplate.opsForSet().intersect(RedisConstant.FOLLOW_KEY + userid, RedisConstant.FOLLOW_KEY + id);
        log.info(intersect.toString());
        List<UserDTO> userList = new ArrayList<>();
        for (String s : intersect) {
            try {
                UserDTO userdto = new UserDTO();
                BeanUtil.copyProperties(userService.getById(objectMapper.readValue(s, Long.class)), userdto);
                userList.add(userdto);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return Result.ok(userList);
    }

    @Override
    public List<Long> getByUserID(Long id) {
        return followMapper.getbyuserid(id);
    }
}
